import React from "react";
import PropTypes from "prop-types";
import { stripesConnect } from "@folio/stripes/core";
import { FormattedMessage, injectIntl } from "react-intl";
import EditForm from "./edit-form";

class FormSachet extends React.Component {
  constructor(props) {
    super(props);
    this.state = { operator: {} };
  }

  static propTypes = {
    history: PropTypes.object,
    match: PropTypes.object,
    resources: PropTypes.object,
    mutator: PropTypes.shape({
      add: PropTypes.shape({
        POST: PropTypes.func.isRequired
      }),
      update: PropTypes.shape({
        PUT: PropTypes.func.isRequired
      }),
      validate: PropTypes.shape({
        reset: PropTypes.func.isRequired,
        GET: PropTypes.func.isRequired
      }).isRequired
    }).isRequired,
    dictionary: PropTypes.object,
    httpValidatorInvoke: PropTypes.object
  };

  editCommit = ({ requestPreferences, creds, ...formData }) => {
    delete formData.rowIndex;
    if (formData) {
      formData.operator = this.state.operator;
      delete formData.operator.addresses;
      delete formData.operator.preferredContactTypeId;
      delete formData.operator.servicePoints;
      delete formData.operator.curServicePoint;
      delete formData.operator.dateOfBirth;
      if (formData.id) {
        this.update(formData);
      } else if (!formData.id) {
        this.add(formData);
      }
    }
  };

  add = data => {
    const { POST } = this.props.httpCall;
    POST(data).then(response => {
      this.props.spitOut();
    });
  };

  update = data => {
    const { PUT } = this.props.httpCall;
    PUT(data).then(response => {
      this.props.spitOut();
    });
  };

  componentDidMount() {
    const { currentUser } = this.props.stripes.okapi;
    if (currentUser) {
      this.setState({
        operator: currentUser
      });
    }
  }

  render() {
    return (
      <EditForm
        onSubmit={this.editCommit}
        initialValues={this.props.editParams}
        cancel={this.props.spitOut}
        httpValidatorInvoke={this.props.httpValidatorInvoke}
      />
    );
  }
}

export default injectIntl(stripesConnect(FormSachet));
